﻿using System.Collections.Generic;
using System.Data;
using Loki.Data;
using Luna.Connectors;

namespace Luna.Data.Configuration
{
    /// <summary>
    /// Mapper for data interface IConnectorData.
    /// </summary>
    public partial class ConnectorDataMapper : LunaMapper<ConnectorData, IConnectorData>
    {
        public ConnectorDataMapper()
        {
            GetAllRequest = "Meta.connector_select_all";
            GetRequest = "Meta.connector_select";
            InsertRequest = "Meta.connector_insert";
            UpdateRequest = "Meta.connector_update";
            DeleteRequest = "Meta.connector_delete";
            GetAllByTypeRequest = "Meta.connector_select_by_type";
        }

        private const string TypeColumnName = "Type";
        private const string LoginColumnName = "Login";
        private const string PasswordColumnName = "Password";
        private const string ParamsColumnName = "Params";

        public string GetAllByTypeRequest { get; set; }

        protected override void LoadCoreData(IConnectorData entity, IDataRecord record)
        {
            entity.Type = record.GetEnum<ConnectorType>(TypeColumnName);
            entity.Login = record.GetString(LoginColumnName);
            entity.Password = record.GetString(PasswordColumnName);
            entity.Params = record.GetString(ParamsColumnName);
        }

        protected override void MapSaveParameters(IDatabaseCommand command, IConnectorData entity)
        {
            command.AddParameter(TypeColumnName, entity.Type);
            command.AddParameter(LoginColumnName, entity.Login);
            command.AddParameter(PasswordColumnName, entity.Password);
            command.AddParameter(ParamsColumnName, entity.Params);
            command.AddParameter(IDParameterName, entity.PK);
        }

        public IEnumerable<IConnectorData> GetAllByType(IDbTransaction transaction, ConnectorType type)
        {
            return ExecuteGetAll(
                    transaction,
                    GetAllByTypeRequest,
                    c =>
                    {
                        c.AddParameter(TypeColumnName, type);
                    });
        }
    }
}